﻿using System.Linq;
using System.Windows.Forms;
using DosTexPrj.Core.Models;
using DosTexPrj.Core.RepositoriesInterface;
using DosTexPrj.Implement.NHibernate;
using System;
using DosTexPrj.UI.WinForm.Commons;

namespace DosTexPrj.UI.WinForm
{
    public partial class LoginForm : Form
    {
        private IUserRepository _userRepository;

        private bool _isLogin;

        public bool IsLogin
        {
            get { return this._isLogin; }
            set { this._isLogin = value; }
        }

        public LoginForm()
        {
            InitializeComponent();
            this._userRepository = MyServiceLocator.DoGetInstance<IUserRepository>();
        }

        private void LoginForm_Load(object sender, System.EventArgs e)
        {
            CreateFormTitle();
        }

        private void btnLogin_Click(object sender, System.EventArgs e)
        {
            Login();
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            Application.Exit();
        }

        #region -- Functions --

        private void Login()
        {
            if (!CheckValidate())
                return;

            var user = this._userRepository.FindByCondition<User>(x => x.Username == txtUsername.Text.Trim() && x.Password == txtPassword.Text.Trim());
            if (user != null && user.Count() > 0)
            {
                IsLogin = true;
                this.Close();
            }
            else
            {
                MessageBox.Show("Login fail!");
            }
        }

        private void CreateFormTitle()
        {
            ctrTitle.FormTitle = "LOGIN TO SYSTEM";
            ctrTitle.BackColor = System.Drawing.Color.White;
        }

        private bool CheckValidate()
        {
            error.Clear();
            bool flag = true;
            if (!Common.IsBlankTextBox(txtUsername, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtPassword, "Required Field", error))
                flag = false;

            return flag;
        }

        #endregion -- Functions --

    }
}